#!/usr/bin/python
# YLRP is not a YouLoc Rover updater Python script
# Hacked by Timo Taskinen from the work of other YouLoc developers and Maemo.org wiki writers.
import location
import gobject
import time
import sys
import httplib, urllib

# Settings
# Used location methods and time interval are taken from the device's control panel.
user_key = "<your imei here>"
version = "$Id:$"

def on_error(control, error, data):
    print "location error: %d... quitting" % error
    data.quit()

def on_changed(device, data):
    if not device:
        return
    if device.fix:
        if device.fix[1] & location.GPS_DEVICE_LATLONG_SET:
            curTime = time.time()
            print "Got new location: lat = %f, lon = %f" % device.fix[4:6]
            lat = device.fix[4]
            lon = device.fix[5]
            speed_knots = device.fix[11] / 1.852
            course_deg = device.fix[9]
            alt = device.fix[7]
            postData( curTime, lat, lon, alt, speed_knots, course_deg )
            print "Updated location: %s, %s" % (lat, lon)
            # data.stop()

def on_stop(control, data):
    print "quitting"
    data.quit()

def start_location(data):
    data.start()
    return False

def postData(time,lat,long,alt,speed_knots,course_deg):
    conn = httplib.HTTPConnection("proto.youloc.net:80")
    url = "/logger.php?imei=%s&time=%s&lat=%s&lon=%s&status=A&alt=%s&speed=%s&course=%s" % (user_key, time, lat, long, alt, speed_knots, course_deg)
    conn.request("GET", url)
    response = conn.getresponse()
    data = response.read()
    print "Got response: %s" % (data)
    conn.close()

loop = gobject.MainLoop()
control = location.GPSDControl.get_default()
device = location.GPSDevice()
control.set_properties(preferred_method=location.METHOD_USER_SELECTED,
                       preferred_interval=location.INTERVAL_DEFAULT)

control.connect("error-verbose", on_error, loop)
device.connect("changed", on_changed, control)
control.connect("gpsd-stopped", on_stop, loop)

gobject.idle_add(start_location, control)

print "YLRP version %s" % (version)
loop.run()
